package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.batch.BatchDeal_Utils
import cn.com.kh.batch.callback.authCallback
import cn.com.kh.batch.callback.signCallback
import cn.com.kh.result.FddResult
import cn.com.kh.result.iAPIResult
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiBatchSignMain
 * @Description: 合同批量签署Main
 *
 */
public class apiBatchSignMain implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiBatchSignMain.class);

    // 获取数据库操作对象
    private static JdbcTemplate jt = new JdbcTemplate();

    // 批次启动暂停的控制Map
    private volatile static Map<String, Integer> stopFlagMap = new HashMap<String, Integer>();

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        long startTime = System.currentTimeMillis();

        jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject res_Json = iAPIResult.ERROR("获取-个人用户信息查询 失败");

        String method = request.getMethod();
        log.debug("获取请求方式：" + method);

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取调用数据
        String callPram = "";
        if (method.equals("GET")) {
            callPram = request.getQueryString();
            log.info("接收调用GET参数信息：" + callPram);
        } else if (method.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callPram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + callPram);
        }

        try {
            // 获取回调类型
            String callback_Type = Util.filterForObject(request.getParameter("callbackType"));
            log.debug("获取回调类型：" + callback_Type);

            // 界面操作暂停批次
            if (callback_Type == "暂停") {
                String batch_Id = Util.filterForObject(request.getParameter("batchId"));
                log.debug("获取" + callback_Type + "调用参数 batch_Id：" + batch_Id);

                if (KHUtil.isNull(batch_Id)) {
                    res_Json = iAPIResult.ERROR("批次ID字段不能为空");

                } else {
                    stopFlagMap.put(batch_Id, 0);
                    res_Json = iAPIResult.SUCCESS("批次暂停操作成功", "");

                }

            } else if (callback_Type == "批量发送") {
                String batch_Id = Util.filterForObject(request.getParameter("batchId"));
                log.debug("获取" + callback_Type + "调用参数 batch_Id：" + batch_Id);

                if (KHUtil.isNull(batch_Id)) {
                    res_Json = iAPIResult.ERROR("批次ID字段不能为空");

                } else {
                    // 标记批次启动
                    stopFlagMap.put(batch_Id, 1);
                    res_Json = BatchDeal_Utils.runDealBatch(jt, batch_Id, stopFlagMap);

                    // 全部执行完毕后移除标记
                    stopFlagMap.remove(batch_Id);
                }

            } else if (callback_Type == "个人认证" || callback_Type == "企业认证") {
                // 接收客户端调用参数
                String rec_Guid = Util.filterForObject(request.getParameter("recGuid"));
                String Cc_CustomerId = Util.filterForObject(request.getParameter("customerId"));
                log.debug("获取" + callback_Type + "调用参数 rec_Guid：" + rec_Guid + " customerId：" + Cc_CustomerId);
                // 回调主键信息不能为空
                if (KHUtil.isNull(rec_Guid)) {
                    res_Json = JSONObject.fromObject(new FddResult(FddResult.WARN, "认证回调 recGuid必传", null));
                } else if (KHUtil.isNull(Cc_CustomerId)) {
                    res_Json = JSONObject.fromObject(new FddResult(FddResult.WARN, "认证回调 customerId必传", null));
                } else {
                    // 处理回调
                    res_Json = authCallback.doAuthCallback(jt, callback_Type, rec_Guid, Cc_CustomerId, callPram);
                }

            } else if (callback_Type == "乙方签署回调") {
                // 接收客户端调用参数
                String rec_Guid = Util.filterForObject(request.getParameter("recGuid"));
                String customerType = Util.filterForObject(request.getParameter("customerType"));
                String agreementDuid = Util.filterForObject(request.getParameter("agreementDuid"));
                log.debug("获取" + callback_Type + "调用参数 rec_Guid：" + rec_Guid + " customerType：" + customerType + " agreementDuid：" + agreementDuid);

                // 回调主键信息不能为空
                if (KHUtil.isNull(rec_Guid)) {
                    res_Json = JSONObject.fromObject(new FddResult(FddResult.WARN, "乙方签署回调recGuid必传", null));

                } else if (KHUtil.isNull(agreementDuid)) {
                    res_Json = JSONObject.fromObject(new FddResult(FddResult.WARN, "乙方签署回调agreementDuid必传", null));

                } else {
                    res_Json = signCallback.doBSignCallback(jt, rec_Guid, agreementDuid, customerType, callPram);

                }

            } else if (callback_Type == "甲方签署回调") {
                //接收客户端调用参数
                String rec_Guid = Util.filterForObject(request.getParameter("recGuid"));
                String customerType = Util.filterForObject(request.getParameter("customerType"));
                String agreementDuid = Util.filterForObject(request.getParameter("agreementDuid"));
                log.debug("获取" + callback_Type + "调用参数 rec_Guid：" + rec_Guid + " customerType：" + customerType + " agreementDuid：" + agreementDuid);

                // 回调主键信息不能为空
                if (KHUtil.isNull(rec_Guid)) {
                    res_Json = JSONObject.fromObject(new FddResult(FddResult.WARN, "甲方签署回调recGuid必传", null));

                } else if (KHUtil.isNull(agreementDuid)) {
                    res_Json = JSONObject.fromObject(new FddResult(FddResult.WARN, "甲方签署回调agreementDuid必传", null));

                } else {
                    res_Json = signCallback.doASignCallback(jt, rec_Guid, agreementDuid, customerType, callPram);
                }

            } else {
                res_Json = JSONObject.fromObject(new FddResult(FddResult.WARN, "回调类型不支持或回调类型为空", null));
            }

        } catch (Exception e) {
            res_Json = iAPIResult.ERROR("合同批量签署Main处理调用异常(" + e.getMessage() + ")");
            log.error("合同批量签署Main处理调用异常：" + e.getMessage(), e);

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "合同批量-控制Main", "apiBatchSignMain", callPram, res_Json.toString(), (System.currentTimeMillis() - startTime).toString(), method + ":" + mapParam.toString());
        }

        log.debug("合同批量签署Main 执行结果：" + res_Json.toString());
        return res_Json.toString();
    }

}